package com.study.ssm.aop.proxy;

import com.study.ssm.factory.bean.User;
import org.springframework.aop.framework.AopContext;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author zhoujunlin
 * @date 2023年07月23日 19:32
 * @desc
 */
public class UserServiceImpl implements UserService, ApplicationContextAware {

    private ApplicationContext ctx;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ctx = applicationContext;
    }

    @Override
    public int register(User user) {
        // 当前方法不能做方法增强  因为不是代理对象
//        this.query("zhoujl", "123456");
//        System.out.println(AopUtils.isAopProxy(this));

        // 方式一: 上下文中获取代理对象
//        UserService userService = ctx.getBean("userService", UserService.class);
//        System.out.println(AopUtils.isAopProxy(userService));
//        userService.query("zhoujl", "root");

        // 方式二:  AopContext中获取 但是需要设置 expose-proxy="true"
        UserService userService = (UserService) AopContext.currentProxy();
        System.out.println(AopUtils.isAopProxy(userService));
        userService.query("zhoujl", "root");

        System.out.println("add user = " + user);
        return 0;
    }

    @Override
    public User query(String username, String password) {
        System.out.println("query username: " + username + ", password:" + password);
        return null;
    }
}
